<template>
  <div class="feedback-management">
    <h2>反馈管理</h2>
    
    <!-- 搜索框 -->
    <div class="search-box">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入员工姓名搜索"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 反馈列表 -->
    <div class="feedback-list">
      <el-table :data="feedbackList" border>
        <el-table-column prop="employeeName" label="员工姓名" width="120" />
        <el-table-column prop="courseName" label="课程名称" width="180" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="反馈内容" />
        <el-table-column prop="createTime" label="提交时间" width="180" />
      </el-table>
    </div>

    <!-- 数据统计 -->
    <div class="feedback-statistics">
      <h3>反馈统计</h3>
      <div class="charts-container">
        <div class="chart">
          <ve-histogram
            :data="courseRatingData"
            :settings="chartSettings"
            height="300px"
          />
        </div>
        <div class="chart">
          <ve-pie
            :data="satisfactionData"
            height="300px"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { API_BASE_URL } from '@/config/api'
import { Search } from '@element-plus/icons-vue'

export default {
  name: 'FeedbackManagement',
  
  components: {
    Search
  },
  
  setup() {
    const store = useStore()
    const feedbackList = computed(() => store.state.feedback.feedbackList)
    const originalFeedbackList = computed(() => store.state.feedback.originalFeedbackList)
    const searchKeyword = ref('')
    
    // 图表配置
    const chartSettings = {
      xAxisName: '课程',
      yAxisName: '平均评分'
    }
    
    const courseRatingData = ref({
      columns: ['课程', '平均评分'],
      rows: []
    })
    
    const satisfactionData = ref({
      columns: ['满意度', '数量'],
      rows: []
    })

    // 获取反馈列表
    const getFeedbackList = async () => {
      try {
        const response = await fetch(`${API_BASE_URL}/getAllEmployeeFeedbacks`, {
          method: 'GET',
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          }
        })  
        
        const result = await response.json()
        console.log('后端返回的原始数据:', result)

        if (result.code === 0 && result.data) {
          const processedData = result.data.map(item => ({
            employeeName: item.employeeName,
            courseName: item.courseName,
            rating: item.mark,
            content: item.content,
            createTime: new Date(item.createTime).toLocaleString('zh-CN'),
            feedbackID: item.feedbackID,
            employeeID: item.employeeID,
            courseID: item.courseID,
            feedbackStatus: item.feedbackStatus
          }))
          
          console.log('处理后的数据:', processedData)
          
          // 使用 Vuex 存储数据
          store.dispatch('saveFeedbackList', processedData)
          generateStatistics()
        } else {
          const errorMessage = result.msg || '获取反馈列表失败'
          ElMessage.error(errorMessage)
        }
      } catch (error) {
        console.error('获取反馈列表失败:', error)
        ElMessage.error('获取反馈列表失败，请检查网络连接')
      }
    }

    // 生成统计数据
    const generateStatistics = () => {
      // 课程评分统计
      const courseRatings = {}
      feedbackList.value.forEach(feedback => {
        if (!courseRatings[feedback.courseName]) {
          courseRatings[feedback.courseName] = []
        }
        courseRatings[feedback.courseName].push(feedback.rating)
      })

      courseRatingData.value.rows = Object.entries(courseRatings).map(([course, ratings]) => ({
        '课程': course,
        '平均评分': ratings.reduce((a, b) => a + b, 0) / ratings.length
      }))

      // 满意度分布统计
      const satisfaction = {
        '非常满意': 0,
        '满意': 0,
        '一般': 0,
        '不满意': 0
      }

      feedbackList.value.forEach(feedback => {
        if (feedback.rating >= 4.5) satisfaction['非常满意']++
        else if (feedback.rating >= 3.5) satisfaction['满意']++
        else if (feedback.rating >= 2.5) satisfaction['一般']++
        else satisfaction['不满意']++
      })

      satisfactionData.value.rows = Object.entries(satisfaction).map(([level, count]) => ({
        '满意度': level,
        '数量': count
      }))
    }

    // 添加搜索方法
    const handleSearch = () => {
      if (!searchKeyword.value) {
        store.commit('SET_FEEDBACK_LIST', [...originalFeedbackList.value])
      } else {
        const filteredList = originalFeedbackList.value.filter(item =>
          item.employeeName.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
        store.commit('SET_FEEDBACK_LIST', filteredList)
      }
      generateStatistics()
    }

    onMounted(() => {
      getFeedbackList()
      window.getFeedbackList =  getFeedbackList
    })

    return {
      feedbackList,
      courseRatingData,
      satisfactionData,
      chartSettings,
      searchKeyword,
      handleSearch
    }
  }
}
</script>

<style scoped>
.feedback-management {
  padding: 20px;
}

.feedback-statistics {
  margin-top: 30px;
}

.charts-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.chart {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.search-box {
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}
</style>
